package com.ruicar.afs.cloud.afscase.loanactivatepool.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruicar.afs.cloud.afscase.infomanagement.entity.CaseBaseInfo;
import com.ruicar.afs.cloud.afscase.infomanagement.service.CaseBaseInfoService;
import com.ruicar.afs.cloud.afscase.infomanagement.service.CaseContractInfoService;
import com.ruicar.afs.cloud.afscase.loanactivatepool.condition.LoanActivateCondition;
import com.ruicar.afs.cloud.afscase.loanactivatepool.service.LoanActivateService;
import com.ruicar.afs.cloud.afscase.loanactivatepool.vo.LoanActivatePoolVO;
import com.ruicar.afs.cloud.afscase.paramconfmanagement.entity.CaseConfParam;
import com.ruicar.afs.cloud.afscase.paramconfmanagement.service.CaseConfParamService;
import com.ruicar.afs.cloud.common.core.log.annotation.SysLog;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.BusinessTypeEnum;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.WhetherEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.Date;

/**
 * @author yk.Li
 * @description 放款待激活池控制层
 * @date 2020/5/18 17:39
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/loanActivate")
@Api("放款待激活池")
public class LoanActivateController {
    private final LoanActivateService service;
    private CaseConfParamService caseConfParamService;
    private CaseContractInfoService caseContractInfoService;
    private CaseBaseInfoService caseBaseInfoService;
    /**
     * Mapper获取放款待激活池数据
     *
     * @param condition
     * @return
     */
    @PostMapping(value = "/getLoanActivateList")
    @ApiOperation(value = "多条件分页获取放款待激活池数据")
    public IResponse<IPage<LoanActivatePoolVO>> getLoanActivateInfoList(@RequestBody LoanActivateCondition condition) {
        if(condition.getStartDate()!=null){
            LocalDateTime startTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(condition.getStartDate().getTime()), ZoneId.systemDefault());
            LocalDateTime endTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(condition.getEndDate().getTime()), ZoneId.systemDefault());
            //获取最小时间 xxxx-xx-xx 0:00:00
            LocalDateTime startOfDay = startTime.with(LocalTime.MIN);
            log.info("获取范围最小时间{}",startOfDay);
            //获取30天前最大时间 xxxx-xx-xx 23:59:59
            LocalDateTime endOfDay = endTime.with(LocalTime.MAX);
            log.info("获取范围最大时间{}",endOfDay);
            condition.setStartDate(Date.from(startOfDay.atZone( ZoneId.systemDefault()).toInstant()));
            condition.setEndDate(Date.from(endOfDay.atZone( ZoneId.systemDefault()).toInstant()));
        }
        IPage<LoanActivatePoolVO> pageResult = service.getLoanActivateInfoList(
                new Page(condition.getPageNumber(), condition.getPageSize()), condition);
        pageResult.getRecords().forEach(result->{
            CaseBaseInfo caseBaseInfo = caseBaseInfoService.getOne(Wrappers.<CaseBaseInfo>query().lambda()
                    .eq(CaseBaseInfo::getApplyNo, result.getApplyNo()));
            if(caseBaseInfo!=null){
                Date lastDate = caseBaseInfo.getPassLastDate();
                if(caseBaseInfo.getPassLastDate()!=null) {
                    if (caseBaseInfo.getBusinessType().equals(BusinessTypeEnum.NEW_CAR.getCode())) {
                        if (((new Date().getTime() - lastDate.getTime() + 1000000) / (60 * 60 * 24 * 1000)) > 59) {
                            result.setIsOverTime(WhetherEnum.YES.getCode());
                        }
                    } else if (caseBaseInfo.getBusinessType().equals(BusinessTypeEnum.OLD_CAR.getCode())) {
                        if (((new Date().getTime() - lastDate.getTime() + 1000000) / (60 * 60 * 24 * 1000)) > 29) {
                            result.setIsOverTime(WhetherEnum.YES.getCode());
                        }
                    }
                }
            }
        });
        return IResponse.success(null != pageResult ? pageResult : "");
    }

    @ApiOperation(value = "提交废弃原因")
    @SysLog("提交废弃原因")
    @RequestMapping(value = "/updateDiscardData/{ids}", method = RequestMethod.POST)
    public IResponse<Boolean> updateDiscardData(@PathVariable Long[] ids) {
        service.updateDiscardData(ids);
        return new IResponse<Boolean>().setMsg("废弃成功，请及时跟进审核状况!");
    }

    @ApiOperation(value = "人工激活")
    @SysLog("人工激活")
    @RequestMapping(value = "/doActivateOfArtificial/{ids}", method = RequestMethod.POST)
    public IResponse<Boolean> doActivateOfArtificial(@PathVariable Long[] ids) {
        service.doActivateOfArtificial(ids);
        return new IResponse<Boolean>().setMsg("激活成功");
    }

    /**
     * 退回放款
     * @param id
     * @return
     */
    @RequestMapping(value = "/submitBackLoan/{id}", method = RequestMethod.POST)
    @ApiOperation(value = "工作流退回放款")
    public IResponse<Boolean> submitBackLoan(@PathVariable Long id) {
        service.submitBackLoan(id);
        return new IResponse<Boolean>().setMsg("退回成功，请及时跟进审核状况!");
    }


    @ApiOperation(value = "修改参数配置")
    @SysLog("修改参数配置")
    @RequestMapping(value = "/changeOnOff/{status}", method = RequestMethod.POST)
    public IResponse changeOnOff(@PathVariable String status) {
        CaseConfParam caseConfParam=caseConfParamService.getOne(Wrappers.<CaseConfParam>query().lambda()
                .eq(CaseConfParam::getParamType,"CONTRACT_AUTO_ACTIVE"));
        caseConfParam.setParamValue(status);
        caseConfParamService.updateById(caseConfParam);
        return new IResponse().setMsg("设置成功");
    }

    //getOnOffStatus
    @ApiOperation(value = "查询当前开关状态")
    @SysLog("查询当前开关状态")
    @RequestMapping(value = "/getOnOffStatus", method = RequestMethod.POST)
    public IResponse<CaseConfParam> getOnOffStatus() {
        CaseConfParam caseConfParam=caseConfParamService.getOne(Wrappers.<CaseConfParam>query().lambda()
                .eq(CaseConfParam::getParamType,"CONTRACT_AUTO_ACTIVE"));
        return new IResponse().setData(caseConfParam);
    }
}
